import { useUserStore, useMenuStore, useConfigStore } from '@/stores'
import { useRouter } from 'vue-router'
import { useAsyncState } from '@vueuse/core'
import { login as toLogin } from '@/api'

export const refresh = async () => {
  const userStore = useUserStore()
  const menuStore = useMenuStore()
  const configStore = useConfigStore()
  await userStore.login()
  await menuStore.refresh(userStore.access)
  await configStore.refresh()
}

export const login = (username: Ref<string>, password: Ref<string>) => {
  const router = useRouter()
  const userStore = useUserStore()
  const isShowPassword = ref(false)

  const { state, isLoading, execute } = useAsyncState(
    (username: string, password: string) => toLogin({ username, password }),
    { token: '' },
    { immediate: false }
  )

  return {
    state,
    isLoading,
    execute,
    isShowPassword,
    onPasswordToggle: () => {
      isShowPassword.value = !isShowPassword.value
    },
    onLogin: async () => {
      await execute(0, username.value, password.value)
      if (state.value) {
        userStore.token = state.value.token
        await refresh()
        router.push({ name: 'home' })
      }
    }
  }
}
